<template>
  <div>
    <el-button type="primary" size="mini" style="width: 60px;margin-left: 40px;margin-top: 20px" @click="closePage">返回
    </el-button>
    <el-row :gutter="13">
      <p></p>
      <el-form ref="elForm" :rules="rules" :model="formData" size="small" label-width="150px">
        <el-col :span="5">
          <el-form-item label="安全隐患级别:" prop="safetyHazardLevel">
            <el-select v-model="formData.safetyHazardLevel" placeholder="请选择安全隐患级别" clearable size="small">
              <el-option v-for="dict in safetyHazardLevelOptions" :key="dict.dictValue" :label="dict.dictLabel"
                         :value="dict.dictValue"/>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="5">
          <el-form-item label="整改状态:" prop="statetype">
            <el-select v-model="formData.statetype" placeholder="请选择整改状态" clearable size="small">
              <el-option v-for="dict in statetypeOptions" :key="dict.dictValue" :label="dict.dictLabel"
                         :value="dict.dictValue"/>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="7">
          <el-form-item label="发现时间:" prop="findtime">
            <el-date-picker
              :disabled="reportingId>1"
              v-model="formData.findtime"
              type="date"
              value-format="yyyy-MM-dd"
            />
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="预计整改完成时间:" prop="completetime">
            <el-date-picker
              v-model="formData.completetime"
              type="date"
              value-format="yyyy-MM-dd"
              :picker-options="pickerTime2"
            />
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item label="隐患图片:" prop="findtime">
            <el-image v-if="fileUrl != null"
                      style="width: 150px; height: 150px; border-radius: 10px;"
                      :src="fileUrl"
                      :preview-src-list="srcList">
            </el-image>
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item label="安全隐患原因:" prop="safetyHazardReason">
            <!--            <vue-editor useCustomImageHandler placeholder="请输入内容" @image-added="handleImageAdded"-->
            <!--                        v-model="formData.safetyHazardReason"></vue-editor>-->
            <el-input
              v-model="formData.safetyHazardReason"
              :autosize="{ minRows: 10, maxRows: 20 }"
              type="textarea"
              placeholder="请输入内容"
            />
          </el-form-item>
        </el-col>

        <el-col :span="24">
          <el-form-item label="隐患整改措施:" prop="hazardCopeMeasures">
            <!--            <vue-editor useCustomImageHandler placeholder="请输入内容" @image-added="handleImageAdded"-->
            <!--                        v-model="formData.hazardCopeMeasures"></vue-editor>-->
            <el-input
              v-model="formData.hazardCopeMeasures"
              :autosize="{ minRows: 10, maxRows: 20 }"
              type="textarea"
              placeholder="请输入内容"
            />
          </el-form-item>
        </el-col>

        <el-col :span="12">
          <el-form-item label="文件上传:" prop="uploadFileList">
            <el-upload style="display: flex;align-items: center" ref="upload"
                       :file-list="uploadFileList"
                       :auto-upload="false"
                       action="#"
                       :on-change="handleChange"
                       :on-remove="handleRemove"
                       :before-upload="uploadInspect"
                       :limit="1">
              <el-button size="small" type="primary" icon="el-icon-upload">选择文件</el-button>
            </el-upload>
            <div style="margin-top: 10px" class="el-upload__tip">提示：只能上传不超过10MB的文件</div>
          </el-form-item>
        </el-col>

        <el-col :span="24">
          <el-form-item size="large">
            <el-button type="primary" @click="submitForm1">提交</el-button>
            <el-button @click="resetForm">重置</el-button>
          </el-form-item>
        </el-col>
      </el-form>
    </el-row>
  </div>
</template>
<script>
import {
  getToken
} from "@/utils/auth";
import {
  VueEditor
} from "vue2-editor";
import axios from "axios";

import {
  getReporting,
  addReporting,
  updateReporting
} from "@/api/patrol/reporting";

export default {
  components: {
    VueEditor
  },
  props: [],
  data() {
    return {
      fileUrl: null,
      srcList: [],
      number: 0,
      Authorization: {
        Authorization: getToken()
      },
      reportingId: null,
      formData: {
        //安全隐患级别
        safetyHazardLevel: null,
        //安全隐患原因
        safetyHazardReason: '',
        //隐患整改措施
        hazardCopeMeasures: '',
        statetype: 0,
        //文件路径
        findtime: null,
        completetime: null,
      },
      rules: {
        safetyHazardLevel: [{
          required: true,
          message: '请选择安全隐患级别',
          trigger: 'blur'
        }],
        safetyHazardReason: [{
          required: true,
          message: '请输入安全隐患原因',
          trigger: 'blur'
        }], findtime: [{
          required: true,
          message: '请选择发现时间',
          trigger: 'blur'
        }], completetime: [{
          required: true,
          message: '请选择预计整改完成时间',
          trigger: 'blur'
        }], statetype: [{
          required: true,
          message: '请选择整改状态',
          trigger: 'blur'
        }], hazardCopeMeasures: [{
          required: true,
          message: '请输入隐患整改措施',
          trigger: 'blur'
        }],
      },
      uploadTheAddress: process.env.VUE_APP_BASE_API,
      // 安全隐患级别字典
      safetyHazardLevelOptions: [],
      statetypeOptions: [
        {'dictValue': 1, 'dictLabel': '整改完成'},
        {'dictValue': 0, 'dictLabel': '整改中'},
        {'dictValue': -1, 'dictLabel': '未整改'}
      ],
      //文件上传路径
      uploadFileList: [],
      fileList: [],
      imgfileList: [],
      pickerTime2: {
        disabledDate(time) {
          return time.getTime() < Date.now() /*- 8.64e7*/;//如果没有后面的-8.64e7就是不可以选择今天的;
        }
      }
    }
  },
  computed: {},
  watch: {},
  created() {
    this.loading = true;
    this.reportingId = this.$route.query.reportingId;
    this.getDicts("safety_hazard_level").then(response => {
      this.safetyHazardLevelOptions = response.data;
      this.loading = false;
    });
  },
  mounted() {
    if (this.reportingId !== "false") {
      getReporting(this.reportingId).then(res => {
        let data = res.data;
        this.formData.safetyHazardLevel = data.safetyHazardLevel.toString();
        this.formData.safetyHazardReason = data.safetyHazardReason;
        this.formData.hazardCopeMeasures = data.hazardCopeMeasures;
        this.formData.submitter = data.submitter;
        this.formData.findtime = data.findtime;
        this.formData.completetime = data.completetime;
        this.formData.statetype = data.statetype;
        this.fileUrl = data.fileUrl;
        if (this.fileUrl != null)
          this.srcList = [data.fileUrl]
        if (data.fileUrl) {
          let urlList = data.fileUrl.split(',');
          urlList.forEach(element => {
            this.imgfileList = [{
              name: element.split('_')[1],
              url: this.uploadTheAddress + element
            }];
          });
        }
        if (data.filePath) {
          let urlList = data.filePath.split(',');
          urlList.forEach(element => {
            this.uploadFileList = [{
              name: element.split('_')[1],
              url: this.uploadTheAddress + element
            }];
          });
        } else {
          this.uploadFileList = [];
        }
        this.loading = false;
      });
    }
  },
  methods: {
    submitForm1() {
      console.log(this.fileList);
      if (this.number > 0) {
        let formData = new FormData()
        for (let index = 0; index < this.fileList.length; index++) {
          formData.append('files', this.fileList[index].raw);
        }
        axios({
          url: process.env.VUE_APP_BASE_API + "/common/multiple/upload",
          method: 'POST',
          headers: this.Authorization,
          data: formData
        }).then(res => {
          console.log(res)
          this.formData.filePath = res.data.fileName
          this.submitForm();
        }).catch(err => {
          console.log(err)
          this.msgError("文件上传失败，请重试")
        })
      } else {
        this.submitForm();
      }
    },
    submitForm() {
      this.$refs['elForm'].validate(valid => {
        if (!valid) return
        if (this.reportingId !== "false") {
          this.$set(this.formData, "id", this.reportingId)
          updateReporting(this.formData).then(res => {
            this.msgSuccess("编辑成功")
            if (res.code === 200) {
              this.$tab.closeOpenPage({
                path: "/patrol/reporting"
              }).then(() => {
                this.$tab.refreshPage()
              });
            }
          })
        } else {
          addReporting(this.formData).then(res => {
            this.msgSuccess("新增成功")
            if (res.code === 200) {
              this.$tab.closeOpenPage({
                path: "/patrol/reporting"
              }).then(() => {
                this.$tab.refreshPage()
              });
            }
          })
        }
      })
    },
    handleChange(files, fileList) {
      this.fileList = fileList
      this.number = fileList.length
    },
    handleRemove(files, fileList) {
      this.fileList = fileList
      this.number = fileList.length
    },
    resetForm() {
      this.$refs['elForm'].resetFields()
    },
    uploadInspect(file) {
      let isRightSize = file.size / 1024 / 1024 <= 50
      if (!isRightSize) {
        this.$message.error('文件名应小于100字符，请修改！')
      }
      let isRightSizex = file.size / 1024 / 1024 <= 10
      if (!isRightSizex) {
        this.$message.error('文件大小超过 10MB,请重新上传！')
      }
      return isRightSize;
    },
    handleImageAdded(file, Editor, cursorLocation, resetUploader) {
      //formDta是个对象，用来模拟表单的
      let formData = new FormData()
      formData.append('file', file)
      //上传图片并回显
      axios({
        url: process.env.VUE_APP_BASE_API + "/common/upload",
        method: 'POST',
        headers: this.Authorization,
        data: formData
      }).then(res => {
        //这两行是关键代码了。在鼠标位置插入图片，数据存的是url
        console.log(res)
        Editor.insertEmbed(cursorLocation, 'image', res.data.url)
        resetUploader()
      }).catch(err => {
        console.log(err)
      })
    },
    //关闭页面
    closePage() {
      this.$store.dispatch('tagsView/delView', this.$route)
      // this.$router.go(-1)
      this.$tab.openPage("安全隐患上报", "/patrol/reporting");
    }
  }
}

</script>
<style scoped>
.el-upload__tip {
  line-height: 1.2;
  margin-top: 0;
}

::v-deep .el-upload-list,
.el-upload-list--text {
  display: flex;
  align-items: center;
}

::v-deep .el-upload-list__item:first-child {
  margin-top: 0;
}

::v-deep .el-transfer-panel {
  width: 300px;
}

::v-deep .el-upload-list__item,
.is-ready {
  margin-left: 10px;
}

::v-deep.el-transfer :nth-child(3) div {
  border: 1px solid #00B3A8;
}

::v-deep.el-transfer :nth-child(3) .el-transfer-panel__header {
  border: 1px solid #00B3A8;
  background: #00B3A8;
}

::v-deep.el-transfer :nth-child(3) .el-transfer-panel__header .el-checkbox__label {
  color: white;
}

::v-deep.el-transfer :nth-child(3) .el-transfer-panel__header .el-checkbox__label span {
  color: white;
}

::v-deep .ql-snow .ql-picker.ql-header .ql-picker-item::before,
::v-deep .ql-snow .ql-picker.ql-header .ql-picker-label::before {
  content: "常规";
}

::v-deep .ql-snow .ql-picker.ql-header .ql-picker-item[data-value="1"]::before,
::v-deep .ql-snow .ql-picker.ql-header .ql-picker-label[data-value="1"]::before {
  content: "标题1";
}

::v-deep .ql-snow .ql-picker.ql-header .ql-picker-item[data-value="2"]::before,
::v-deep .ql-snow .ql-picker.ql-header .ql-picker-label[data-value="2"]::before {
  content: "标题2";
}

::v-deep .ql-snow .ql-picker.ql-header .ql-picker-item[data-value="3"]::before,
::v-deep .ql-snow .ql-picker.ql-header .ql-picker-label[data-value="3"]::before {
  content: "标题3";
}

::v-deep .ql-snow .ql-picker.ql-header .ql-picker-item[data-value="4"]::before,
::v-deep .ql-snow .ql-picker.ql-header .ql-picker-label[data-value="4"]::before {
  content: "标题4";
}

::v-deep .ql-snow .ql-picker.ql-header .ql-picker-item[data-value="5"]::before,
::v-deep .ql-snow .ql-picker.ql-header .ql-picker-label[data-value="5"]::before {
  content: "标题5";
}

::v-deep .ql-snow .ql-picker.ql-header .ql-picker-item[data-value="6"]::before,
::v-deep .ql-snow .ql-picker.ql-header .ql-picker-label[data-value="6"]::before {
  content: "标题6";
}

</style>
